/*
 * Copyright(c) 2020-2100 万达信息股份有限公司 版权所有
 * WONDERS INFORMATION CO., LTD. ALL RIGHTS RESERVED.
 */

package com.wondersgroup.controller;

import com.wondersgroup.config.RestTemplateConfig;
import com.wondersgroup.feignclients.ProductClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * @author: huym
 * @version: 1.0
 * @date: 2020/11/23
 */
@RestController
public class UserController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ProductClient productClient;

    /**
     * 通过RestTemplate直接调用
     */
    @GetMapping("/user/getProductInfo")
    public Map<String, Object> getProductInfo(String id){
        RestTemplate restTemplate = new RestTemplate();
        Map<String, Object> map = restTemplate.getForObject("http://localhost:9098/product/find?id="+id, Map.class);
        return map;
    }

    /**
     * Ribbon
     * @param id
     * @return
     */
    @GetMapping("/user/discoveryClient")
    public List<ServiceInstance> discoveryClient(String id){
        List<ServiceInstance> products = discoveryClient.getInstances("product");
        return products;
    }

    /**
     * Ribbon
     * @return
     */
    @GetMapping("/user/getServiceInstance")
    public ServiceInstance getServiceInstance(){
        return loadBalancerClient.choose("product");
    }

    /**
     * RestTemplate + Ribbon
     * @param id
     * @return
     */
    @GetMapping("/user/getProductInfo2")
    public String getProductInfo2(String id){
        String forObject = restTemplate.getForObject("http://product/product/find?id=" + id, String.class);
        return forObject;
    }

    /**
     * RestTemplate + OpenFeign
     * @param id
     * @return
     */
    @GetMapping("/user/getProductInfo3")
    public Map<String, Object> getProductInfo3(String id){
        return productClient.find(id);
    }

}
